﻿using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SqlSugar;
using Warehouse.Entites;
using Warehouse.Services.Repository;
using WCS.Entities;
using WCS.Entities.Api;

namespace JuionWareHouse.Controllers
{
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class SingBoxController : ControllerBase
	{
		private readonly ILogger<SingBoxController> _logger;
		private readonly Repository<SingleBox> boxRepository;

		public SingBoxController(ILogger<SingBoxController> logger, Repository<SingleBox> boxRepository)
		{
			_logger = logger;
			this.boxRepository = boxRepository;
		}

		/// <summary>
		/// 分页查找
		/// </summary>
		/// <param name="page">当前页码</param>
		/// <param name="limit">每页大小</param>
		/// <param name="query">查询条件</param>
		/// <returns></returns>
		[HttpGet]
		public async Task<ApiResult> GetParksByPage(
			int page, 
			int limit, 
			[FromQuery] string? query)
		{
			RefAsync<int> total = 0;
			try
			{
				if (query != null)
				{
					JObject jobject = JObject.Parse(query);
					var models = new List<IConditionalModel>();
					foreach (var key in jobject.Properties())
					{
						if (string.IsNullOrEmpty(key.Value.ToString()))
							continue;
						if (key.Value.ToString() == "true" || key.Value.ToString() == "false")
							key.Value = key.Value.ToString() == "true" ? "1" : "0";
						if (key.Path.ToString() == "startDate")
						{
                            models.Add(new ConditionalModel()
                            { FieldName = nameof(SingleBox.Time), FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.GreaterThanOrEqual });
							continue;
						}
                        if (key.Path.ToString() == "endDate")
                        {
                            models.Add(new ConditionalModel()
                            { FieldName = nameof(SingleBox.Time), FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.LessThanOrEqual });
							continue;
                        }
                        else
							models.Add(new ConditionalModel()
							{ FieldName = key.Name, FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.Like });
					}

                    var parks = await boxRepository.QueryAsync(models, page, limit, total);
                    parks.ForEach(x => x.StockAgeDays = CalcStockAgeDays(x));
                    return ApiResultHelp.Success(new { list = parks, total = total.Value });
				}
				else
				{
					var parks = await boxRepository.QueryAsync(page, limit, total);
					parks.ForEach(x => x.StockAgeDays = CalcStockAgeDays(x));
                    return ApiResultHelp.Success(new { list = parks, total = total.Value });
				}
			}
			catch (Exception ex)
			{
				return ApiResultHelp.Error($"查询出错:{ex.Message}");
			}
		}

		private static string CalcStockAgeDays(SingleBox singleBox)
		{
			if (string.IsNullOrWhiteSpace(singleBox.Time))
			{
				return string.Empty;
			}

			if (!DateTime.TryParse(singleBox.Time, out var outTime))
			{
				return string.Empty;
			}

			var days = (DateTime.Now.Date - outTime.Date).Days;

			return days.ToString();
		}
	}
}
